package org.example.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.example.config.SpringBootBeanAutowiringSupport;
import org.example.service.LdapService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: LiFuqiang
 * @Date: 2020/9/27 15:20
 * @Version 1.0
 */
public class LoginFilter extends UsernamePasswordAuthenticationFilter {

    @Autowired
    LdapService ldapService;

    @Autowired
    SessionRegistry sessionRegistry;

    public LoginFilter() {
        SpringBootBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
    }

    @SneakyThrows
    public Authentication attemptAuthentication2(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

        ObjectMapper mapper = new ObjectMapper();
        Map<String, String[]> result = null;
        //result = mapper.readValue(request.getReader(), Map.class);
        result = request.getParameterMap();
        String username = result.get("username")[0];
        String password = result.get("password")[0];

        Authentication authentication = null;

        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                username, password);

        try {
            if (ldapService.authenticate(username, password)) {
                Collection<SimpleGrantedAuthority> authorities = ldapService.listGroups(username)
                        .stream()
                        .map(x -> new SimpleGrantedAuthority(x))
                        .collect(Collectors.toList());
                authentication = new UsernamePasswordAuthenticationToken(username, authorities);
                sessionRegistry.registerNewSession(request.getSession(true).getId(), username);
            }
        } catch (Exception e) {
            throw new AuthenticationException(e.getMessage(), e) {
                @Override
                public String getMessage() {
                    return super.getMessage();
                }
            };
        }
        return authentication;
    }

    @SneakyThrows
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

        ObjectMapper mapper = new ObjectMapper();
        Map<String, String[]> result = null;
        //result = mapper.readValue(request.getReader(), Map.class);
        result = request.getParameterMap();
        String username = result.get("username")[0];
        String password = result.get("password")[0];

        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                username, password);

        Authentication authentication = null;
        try {
            authentication = this.getAuthenticationManager().authenticate(authRequest);
          //  sessionRegistry.registerNewSession(request.getSession(true).getId(), username);

            // 创建一个 cookie对象
            Cookie cookie = new Cookie("token", "123456");
            cookie.setDomain("bigdata.bddev.virtueit.net");
            cookie.setMaxAge(86400);
            cookie.setPath("/");
            // 将cookie对象加入response响应
            response.addCookie(cookie);
            response.addHeader("token","123456");

        } catch (Exception e) {
            throw new AuthenticationException(e.getMessage(), e) {
                @Override
                public String getMessage() {
                    return super.getMessage();
                }
            };
        }

        return authentication;
    }
}
